package net.wangds.auth.module.impls.defaults;

import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import net.wangds.auth.module.Grant;
import net.wangds.auth.module.GrantOwnerTypeEnum;
import net.wangds.auth.module.PrivilegeActionEnum;
import net.wangds.auth.module.ResourceSchemaEnum;
import net.wangds.data.impl.IdCreate;
import net.wangds.log.helper.LogHelper;
import org.apache.commons.lang3.StringUtils;

import javax.persistence.Column;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.MappedSuperclass;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 默认权限.
 */
@NoArgsConstructor
@MappedSuperclass
public class DefaultGrant extends IdCreate implements Grant {

    private static final long serialVersionUID = 0;
    /**
     * 属主id.
     */
    @Getter
    @Setter
    @Column(length = 36)
    private String ownerId;

    /**
     * 权限属主类型.
     */
    @Getter
    @Setter
    @Enumerated(EnumType.ORDINAL)
    private GrantOwnerTypeEnum ownerType;

    /**
     * 资源id.
     */
    @Getter
    @Setter
    @Column(length = 36)
    private String resId;

    /**
     * 授权动作.
     * @see PrivilegeActionEnum
     */
    @Getter
    @Setter
    @Column()
    private int action;

    /**
     * 权限域.
     */
    @Getter
    @Setter
    @Enumerated(EnumType.STRING)
    @Column(name="protocol")
    private ResourceSchemaEnum schema;

    /**
     * 系统.
     */
    @Getter
    @Setter
    @Column(length=50)
    private String sys;


    /**
     * 模块.
     */
    @Getter
    @Setter
    @Column(length=50)
    private String module;

    /**
     * 特性.
     */
    @Getter
    @Setter
    @Column(length=50)
    private String feature;

    /**
     * 活动.
     */
    @Getter
    @Setter
    @Column(length=50)
    private String activity;

    @Override
    public URL toUrl(){
        try {
            StringBuilder sb = new StringBuilder();
            sb.append(schema).append("://");


            if(StringUtils.isNotBlank(sys)){
                sb.append("/").append(sys);
            }else{
                sb.append("/");
            }

            if(StringUtils.isNotBlank(module)){
                sb.append("/").append(module);
            }else{
                sb.append("/");
            }

            if(StringUtils.isNotBlank(feature)){
                sb.append("/").append(feature);
            }else{
                sb.append("/");
            }

            if(StringUtils.isNotBlank(activity)){
                sb.append("/").append(activity);
            }else{
                sb.append("/");
            }

            sb.append("#action=").append(action);

            return new URL(sb.toString());
        } catch (MalformedURLException e) {
            LogHelper.error(e);
        }
        return null;
    }

}
